﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using com.lover.common;
using System.IO;
using com.lover.astd.common.model;
using com.lover.astd.common.manager;
using com.lover.common.http;

namespace com.lover.astd.common.partner.impl
{
    public class _4399Login : LoginImplBase
    {
        public _4399Login() : base() { }
        public override LoginResult login(ref List<Cookie> cookies, string verify_code = null, string extra = null)
        {
            LoginResult result = new LoginResult();
            logging();
            string encode_password = _password;
            //first des encrypt, then string to hex string
            

            string loginurl = "http://ptlogin.4399.com/ptlogin/login.do?v=1";
            string data = String.Format(
                "loginFrom=uframe&postLoginHandler=default&layoutSelfAdapting=true&externalLogin=qq&displayMode=embed&layout=vertical&appId=www_home&gameId=&css=&redirectUrl=&sessionId=&mainDivId=popup_login_div&includeFcmInfo=false&username={0}&password={1}",
                _username, _password);
            HttpResult resp = TransferMgr.doPostPure(loginurl, data, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }

            // 检查cookie吧还是
            bool login_success = false;
            foreach (Cookie cook in cookies)
            {
                if (cook.Name.Equals("ck_accname")) { login_success = true; break; }
            }
            if (!login_success)
            {
                result.StatusCode = LoginStatusCode.FailInLogin;
                return result;
            }

            string redirecturl = String.Format("http://web.4399.com/stat/togame.php?target=astd&server_id=S{0}", _acc.ServerId);
            resp = TransferMgr.doGetPure(redirecturl, ref cookies);

            // 这里有2种情况, 一种是直接302到游戏的, 另外一种是iframe内嵌游戏的
            string location = resp.getExtraHeader("Location");
            if (location != null && location != "")
            {
                processStartGame(location, result, ref cookies);
                return result;
            }

            string content = resp.getContent();
            Match m = Regex.Match(content, "<iframe.*?src=['\"]+([^'\"]*)['\"]+");
            if (m == null || m.Groups == null || m.Groups.Count < 2)
            {
                result.StatusCode = LoginStatusCode.FailInGetSession;
                return result;
            }
            string gameurl = m.Groups[1].Value;

            processStartGame(gameurl, result, ref cookies);

            return result;
        }
    }
}
